import { LoadingOutlined, ReloadOutlined } from '@ant-design/icons'
import client, { DatasourceInstanceVo } from '@lib/client'
import { Card, CardTable, Toolbar } from '@lib/components'
import { useClientRequest } from '@lib/utils/useClientRequest'
import { Button, message, Popconfirm, Space, Switch, Tooltip } from 'antd'
import { IColumn } from 'office-ui-fabric-react/lib/DetailsList'
import { ScrollablePane } from 'office-ui-fabric-react/lib/ScrollablePane'
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import CreateInstanceButton from './CreateInstanceButton'
import UpdateInstanceButton from './UpdateInstanceButton'

interface IExpandedInstanceItem extends DatasourceInstanceVo {
  key: string
}

function expandInstanceItems(
  rows: DatasourceInstanceVo[]
): IExpandedInstanceItem[] {
  const expanded: IExpandedInstanceItem[] = []
  rows.forEach((row) => {
    expanded.push({
      key: row.id ? row.id + '' : '',
      ...row,
    })
  })
  return expanded
}

export default function InstanceList() {
  const { t } = useTranslation()

  const {
    data: listInstancesResponse,
    isLoading,
    error,
    sendRequest: listInstance,
  } = useClientRequest((reqConfig) =>
    client.getInstance().listInstances(reqConfig)
  )

  const instanceData = useMemo(
    () => expandInstanceItems(listInstancesResponse?.instances ?? []),
    [listInstancesResponse]
  )

  const handleDeleteInstance = async (instanceId) => {
    const r = await client.getInstance().deleteInstance({ id: instanceId })
    if (r.status == 200) {
      message.success('Success')
      await listInstance()
    }
  }

  const handleStatusChange = async (checked, instanceId) => {
    const r = await client
      .getInstance()
      .updateInstanceStatus({ id: instanceId, status: checked ? 1 : 0 })
    if (r.status == 200) {
      message.success('Success')
      await listInstance()
    }
  }

  const handleTestConnection = async (instanceId, instanceName) => {
    const r = await client.getInstance().testConnection(instanceId)
    if (r.status == 200 && r.data.success === true) {
      message.success(
        instanceName + ' ' + t('instance_info.button.test_connection.success')
      )
    } else {
      message.error(
        instanceName + ' ' + t('instance_info.button.test_connection.fail')
      )
    }
  }

  const columns: IColumn[] = useMemo(
    () => [
      {
        name: t('instance_info.list.instance_table.columns.id'),
        key: 'id',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return row.id
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.name'),
        key: 'name',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return row.name
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.address'),
        key: 'address',
        minWidth: 150,
        maxWidth: 300,
        onRender: (row: IExpandedInstanceItem) => {
          return row.address
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.username'),
        key: 'username',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return row.username
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.password'),
        key: 'password',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return row.password
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.index'),
        key: 'index',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return row.index
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.status'),
        key: 'status',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return (
            <Switch
              checked={row.status === 1}
              onChange={(checked) => handleStatusChange(checked, row.id)}
            ></Switch>
          )
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.test'),
        key: 'test',
        minWidth: 100,
        maxWidth: 150,
        onRender: (row: IExpandedInstanceItem) => {
          return (
            <Button
              type="primary"
              shape="round"
              size="small"
              onClick={() => handleTestConnection(row.id, row.name)}
            >
              {t('instance_info.button.test_connection.title')}
            </Button>
          )
        },
      },
      {
        name: t('instance_info.list.instance_table.columns.action'),
        key: 'action',
        minWidth: 100,
        maxWidth: 300,
        onRender: (row: IExpandedInstanceItem) => {
          return (
            <Space>
              <Popconfirm
                placement="bottom"
                title={t('instance_info.button.delete_instance.tip')}
                onConfirm={() => handleDeleteInstance(row.id)}
                okText={t('instance_info.button.delete_instance.submit')}
                cancelText={t('instance_info.button.delete_instance.cancel')}
              >
                <a href="">{t('instance_info.button.delete_instance.title')}</a>
              </Popconfirm>
              <UpdateInstanceButton
                refresh={listInstance}
                instanceId={row.id}
              />
            </Space>
          )
        },
      },
    ],
    [t]
  )

  return (
    <div
      style={{
        height: 'calc(100vh - 48px)',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      <Card>
        <Toolbar>
          <Space>
            <CreateInstanceButton refresh={listInstance} />
          </Space>
          <Space>
            <Tooltip title={t('statement.pages.overview.toolbar.refresh')}>
              {isLoading ? (
                <LoadingOutlined />
              ) : (
                <ReloadOutlined onClick={listInstance} />
              )}
            </Tooltip>
          </Space>
        </Toolbar>
      </Card>

      <div style={{ height: '100%', position: 'relative' }}>
        <ScrollablePane>
          <CardTable
            cardNoMarginTop
            loading={isLoading}
            columns={columns}
            items={instanceData}
            errors={[error]}
          />
        </ScrollablePane>
      </div>
    </div>
  )
}
